# AgriculturalAutomaticMonitoringSystem.py
import DHT11 as dht
import i2c_lcd1602 as iic
import ircontrol as ir
import photoresistor as ph
import rain_detector as rain
import PCF8591 as ADC
import pylirc, time
import RPi.GPIO as GPIO
import math

book = True
devicedata = []

def makerobo_setup(): # 整体初始化
    ir.makerobo_setup()
    dht.makerobo_setup()
    ph.makerobo_setup()
    rain.makerobo_setup()

def makerobo_main(): #主函数
    global devicedata
    devicedata.clear()
    global book
    flag = True
    # 获取温湿度信息
    result=dht.read_dhtll_dat()
    if result:
        humidity, temperature=result
        if humidity > 80:
            flag = False
        if temperature > 40:
            flag = False
    else:
        humidity = 50
        temperature = 26
    s1 = humidity.__str__() + "%RH" + " " + temperature.__str__() + " C°"
    devicedata.append(humidity)
    devicedata.append(temperature)
    #光照信息
    num1 = ph.makerobo_loop()
    s2 = "PV:" + num1.__str__()
    devicedata.append(num1)
    if num1 > 2500:
        flag = False
    #雨滴信息
    num2 = rain.makerobo_loop()
    devicedata.append(num2)
    s2 += " RV:" + num2.__str__()
    if num2 <= 150:
        flag = False
    iic.setup(s1,s2)
    #出现不良情况红灯报警
    if flag == False:
        if book == True:
            ir.RGB_control('KEY_NUMERIC_3')
            ir.makerobo_ledColorSet(ir.rgb_color)
            book = False
    else:
        if book == False:
            ir.RGB_control('KEY_NUMERIC_1')
            ir.makerobo_ledColorSet(ir.rgb_color)
            book = True
    #人们发现不良情况后按1解除红灯报警
    s = pylirc.nextcode(1)
    while(s):
        for (code) in s:
            tt = code["config"]
            ir.RGB_control(code["config"])
            ir.makerobo_ledColorSet(ir.rgb_color)
        if(not ir.makerobo_blocking):
            s = pylirc.nextcode(1)
        else:
            s = []
    time.sleep(1)
    return devicedata

def makerobo_destory():
    ir.destory()
    dht.destory()
    rain.makerobo_destory()
    iic.destory()

if __name__ == '__main__':
    try:
        makerobo_setup()
        makerobo_main()
    except KeyboardInterrupt:
        makerobo_destroy()